package com.hhq.android_web;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hhq.android_web.tools.GifImageView;
import com.hhq.android_web.tools.MyWhat;


public class MainActivity extends AppCompatActivity {

    String TAG = "HHQ";
    private TextView tv;
    private EditText ed;
    private Button btn, btn_break, btn_stop, btn_clear;

    App app = null;
    String page="";
    void setToTextView(String newStr, boolean isEnd)
    {
        tv.setText(page+ newStr);
        if( isEnd ) page += newStr;
    }
    Handler hand1 = new Handler((message)->{
        if(message.what == MyWhat.MESS_OK){
            System.out.println("HHQ:主线曾收到了一个消息");
            Frame f = (Frame) message.obj;
            String res = app.getStringFromFrame(f);
            System.out.println("HHQ:"+ res);
            if(f.type == 15)
                res += "\n\n用户:";
            setToTextView(res, f.type==15 );
            refresh2(tv);
        }else if(message.what == MyWhat.THREAD_BREAK ){
            System.out.println("HHQ:主线曾收到了一个消息,重启子线程");
            setToTextView("[子线程已经退出，请重启!]", true );
            refresh2(tv);
        }
        return false;
    });
    Handler hand2=null;
    private int[] Imgs = {R.drawable.girl1, R.drawable.girl2};
    private int ImagID=0;

    GifImageView gif;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);
        tv.setMovementMethod(ScrollingMovementMethod.getInstance());
        ed = findViewById(R.id.ed);
        btn = findViewById(R.id.btn);
        btn_break = findViewById(R.id.btn_break);
        btn_clear = findViewById(R.id.btn_clear);
        btn_stop = findViewById(R.id.btn_stop);
        gif = findViewById(R.id.gif);
        gif.setMovieResource(R.drawable.gif_searching);


        handlePermission();

        app = new App("125.216.242.232", 8000 );
        app.hand1 = hand1;
        hand2 = app.hand2;

        new Thread(()->{
            if( app.start()){
                setToTextView("成功连接\n\n用户:", true);
                app.BeginRecv( );
            }else{
                tv.setText("失败连接");
            }
        }).start();


        // 发送给 sender
        btn.setOnClickListener(view -> {
            String s =  ed.getText().toString();
            setToTextView(s+"\n6B:", true);
            refresh2(tv);
            ed.setText("");

            Message ms = new Message();
            ms.what =  MyWhat.MESS_OK;
            ms.obj = s;
            hand2.sendMessage(ms);
        });
        btn_break.setOnClickListener(view -> {
            Message ms = new Message();
            ms.what =  MyWhat.MESS_OK;
            ms.obj = "break";
            hand2.sendMessage(ms);
        });
        btn_clear.setOnClickListener(view -> {
            Message ms = new Message();
            ms.what =  MyWhat.MESS_OK;
            ms.obj = "clear";
            hand2.sendMessage(ms);
        });
        btn_stop.setOnClickListener(view -> {
            Message ms = new Message();
            ms.what =  MyWhat.MESS_OK;
            ms.obj = "stop";
            hand2.sendMessage(ms);
        });




    }

    /**
     * 检查app是否拥有存储权限，如果没有的话，提醒用户开启权限
     */
    public void handlePermission() {
        // 检查是否开启 Manifest.permission.xxx
        // (xxx 为权限，根据自己需求添加）
        if (ActivityCompat.checkSelfPermission(this,  Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission has been allowed", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "ask for permission",Toast.LENGTH_SHORT).show();
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            Log.d(TAG, "handlePermission: has aksed");
        }
    }
    public void refresh2(TextView mPingResult ) {
        //let text view to move to the last line.
        int offset = mPingResult.getLineCount() * mPingResult.getLineHeight();
        mPingResult.scrollTo( 0, offset -  400 );

    }

}
